﻿using TCommon;
using TCommunication.FormatIo;
using TCommunication.Interface;
using TCommunication.Model.Enum;

namespace TCommunication.Impl;

public class SkdCanBox:ICanBox
{
    private ICommunication? _communication;

    /// <summary>
    /// 连接名
    /// </summary>
    public string CommunicationName { get; set; } = string.Empty;

    /// <summary>
    /// Can波特率
    /// </summary>
    public CanBaud CanBaud { get; set; } = CanBaud.B10K;

    #region 接口方法实现

    public bool IsConnected => this._communication != null;

    /// <summary>
    /// 创建Can通道
    /// </summary>
    /// <param name="channel"></param>
    /// <returns></returns>
    public OperateResult<ICanChannel> CreateChannel(int channel)
    {
        if (this._communication != null)
        {

            var canChannel = new SkdCanChannel(channel, CanBaud, _communication);
            return OperateResult.CreateSuccessResult<ICanChannel>(canChannel);
        }
        else
        {
            return OperateResult.CreateFailedResult<ICanChannel>("请先连接Can卡");
        }
    }

    public OperateResult Connect()
    {
        if (IsConnected)
        {
            return OperateResult.CreateSuccessResult();
        }
        var result = CommunicationManager.Default.GetCommunication(CommunicationName);
        if (result.IsSuccess)
        {
            this._communication = result.Content!;

            var operateResult = _communication.Connect();
            return operateResult;
        }
        else
        {
            return OperateResult.CreateFailedResult(result.Message);
        }
    }

    public OperateResult DisConnect()
    {
        return this._communication?.DisConnect() ?? OperateResult.CreateSuccessResult();
    }
    /// <summary>
    /// 释放对象
    /// </summary>
    public void Dispose()
    {
        this._communication?.Dispose();
    }

    #endregion

    #region 通讯实现
    /// <summary>
    /// 只写
    /// </summary>
    /// <param name="cmd"></param>
    /// <returns></returns>
    protected virtual OperateResult WriteOnly(string cmd)
    {
        if (_communication is VisaSerialCommunication serialCommunication)
        {
            var rs232FormatIo = new Rs232FormatIo(serialCommunication);
            var result = rs232FormatIo.Write(cmd);
            return result;
        }
        else
        {
            return OperateResult.CreateFailedResult("当前连接非串口连接");
        }
    }
    /// <summary>
    /// 写并读
    /// </summary>
    /// <param name="cmd">指令</param>
    /// <returns></returns>
    protected virtual OperateResult<string> SendAndReceived(string cmd)
    {
        if (_communication is VisaSerialCommunication serialCommunication)
        {
            var rs232FormatIo = new Rs232FormatIo(serialCommunication);
            var result = rs232FormatIo.SendAndReceived(cmd);
            return result;
        }
        else
        {
            return OperateResult.CreateFailedResult<string>("当前连接非串口连接");
        }
    }

    #endregion
}